package com.caigou.modules.tools.ui

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.*
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.modules.tools.R
import com.caigou.modules.tools.adapter.ActiveBannerAdapter
import com.caigou.modules.tools.adapter.TaskListPagerAdapter
import com.caigou.modules.tools.bean.ActiveBean
import com.caigou.modules.tools.bean.RedPackageBean
import com.caigou.modules.tools.bean.UserSignInBean
import com.caigou.modules.tools.databinding.FragmentActiveBinding
import com.caigou.modules.tools.viewmodel.ToolsViewModel
import com.caigou.modules.tools.widget.OpenPackageDialog
import com.caigou.modules.tools.widget.SignInDialog
import com.caigou.modules.tools.widget.SignInRuleDialog
import com.google.android.material.tabs.TabLayoutMediator
import com.zhpan.bannerview.constants.PageStyle
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/10/14
 */
@AndroidEntryPoint
class ActiveFragment : BaseFragment() {

    private var _binding: FragmentActiveBinding? = null
    private val binding get() = _binding!!

    private val toolViewModel: ToolsViewModel by viewModels()
    private var todayTaskListFragment: TodayTaskListFragment? = null
    private var dailyTaskListFragment: DailyTaskListFragment? = null
    private var medalTaskListFragment: MedalTaskListFragment? = null


    private val itemNames = mutableListOf(
        "今日任务",
        "日常活动",
        "勋章活动"
    )

    private val fragments = mutableListOf<Fragment>()

    private val taskListPagerAdapter: TaskListPagerAdapter by lazy {
        TaskListPagerAdapter(this)
    }


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentActiveBinding.inflate(inflater, container, false)
        return _binding?.root
    }


    override fun initView() {
        todayTaskListFragment = TodayTaskListFragment()
        dailyTaskListFragment = DailyTaskListFragment()
        medalTaskListFragment = MedalTaskListFragment()
        binding.activeSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                toolViewModel.getActiveInfo(AppBackgroundInfo.instance.userBean!!.userId)
            }
        }

        binding.activeBvpBanner.apply {
            setLifecycleRegistry(lifecycle)
            setAdapter(ActiveBannerAdapter())
            setInterval(5000)
                .setPageMargin(dp2px(requireActivity(), 10f))
                .setScrollDuration(800)
                .setRevealWidth(dp2px(requireActivity(), 10f), dp2px(requireActivity(), 10f))
                .setPageStyle(PageStyle.MULTI_PAGE)
        }.create()

        binding.activeLayoutTaskList.layoutActiveTaskListViewPager2.adapter = taskListPagerAdapter
        binding.activeLayoutTaskList.layoutActiveTaskListViewPager2.isUserInputEnabled = false
        TabLayoutMediator(
            binding.activeLayoutTaskList.layoutActiveTaskListTabLayout,
            binding.activeLayoutTaskList.layoutActiveTaskListViewPager2,
            true,
            true
        ) { tab, position ->
            tab.text = itemNames[position]
        }.attach()

        fragments.add(todayTaskListFragment!!)
        fragments.add(dailyTaskListFragment!!)
        fragments.add(medalTaskListFragment!!)

        taskListPagerAdapter.setList(fragments)
        binding.activeLayoutTaskList.layoutActiveTaskListViewPager2.offscreenPageLimit = itemNames.size
        binding.activeLayoutTaskList.layoutActiveTaskListViewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                val view = fragments[position].view
                view?.let {
                    updatePagerHeightForChild(it, binding.activeLayoutTaskList.layoutActiveTaskListViewPager2)
                }
            }
        })

        binding.activeLayoutHeader.activeHeaderIvCurrentLv.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_INFO)
                .withString(AppConstants.TARGET_FRAGMENT_TAG, RouterPath.Personal.TAG_LEVEL)
                .navigation()
        }

        binding.activeLayoutHeader.activeHeaderIvNextLv.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_INFO)
                .withString(AppConstants.TARGET_FRAGMENT_TAG, RouterPath.Personal.TAG_LEVEL)
                .navigation()
        }

        binding.activeLayoutSign.activeSignTvRule.setOnClickListener {
            val dialog = SignInRuleDialog(requireActivity())
            dialog.show()
        }

        binding.activeLayoutSign.activeSignBtnSignIn.setOnClickListener {
            toolViewModel.setUserSignIn(AppBackgroundInfo.instance.userBean!!.userId)
        }

        binding.activeTvBack.setOnClickListener {
            (requireActivity() as ToolsActivity).onBackPressed()
        }

        LiveDataBus.get().with(BusKey.GET_RED_PACKAGE, Any::class.java).observe(this) {
            toolViewModel.getRedPackage(AppBackgroundInfo.instance.userBean!!.userId, 11)
        }
    }

    override fun lazyLoad() {
        toolViewModel.getActiveInfo(AppBackgroundInfo.instance.userBean!!.userId)
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(toolViewModel.activeLiveData, ::handleActiveInfo)
        observe(toolViewModel.userSignInLiveData, ::handleUserSignIn)
        observe(toolViewModel.redPackageLiveData, ::handleGetRedPackage)
    }

    override fun onBack() {
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun handleActiveInfo(result: Resource<ActiveBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.activeSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取活动信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.activeSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    return
                }

                handleHeaderInfo(result.data!!)
                if (result.data!!.signInTask.taskProgress > 0) {
                    handleSignInFlower(result.data!!.signInTask.taskProgress)
                }
                if (result.data!!.signInTask.status == 1) {
                    handleSignInButton(true)
                } else {
                    handleSignInButton(false)
                }
                binding.activeBvpBanner.refreshData(result.data!!.bannerList)
                todayTaskListFragment!!.setTaskList(result.data!!.todayList)
                dailyTaskListFragment!!.setTaskList(result.data!!.dailyList)
                medalTaskListFragment!!.setTaskList(result.data!!.medalList)
            }
        }
    }

    private fun handleUserSignIn(result: Resource<UserSignInBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("签到异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                val dialog = SignInDialog(result.data!!.flowerNum, requireActivity())
                dialog.show()

                handleSignInFlower(result.data!!.signCount)
                handleSignInButton(false)
            }
        }
    }

    private fun handleGetRedPackage(result: Resource<RedPackageBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("领取红包异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                val dialog = OpenPackageDialog(result.data!!.money, requireActivity())
                dialog.show()
            }
        }
    }

    private fun handleHeaderInfo(bean: ActiveBean) {
        binding.activeLayoutHeader.activeHeaderTvActionNum.text = bean.actionSize.toString()
        binding.activeLayoutHeader.activeHeaderTvUnreceivedNum.text = bean.unreceivedSize.toString()
        binding.activeLayoutHeader.activeHeaderTvBalanceNum.text = bean.balance.toString()
        binding.activeLayoutHeader.activeHeaderTvFlowerNum.text = bean.flower.toString()

        binding.activeLayoutHeader.activeHeaderTvNextGrowth.text = "${bean.nextGrowthValue}成长值"
        binding.activeLayoutHeader.activeHeaderTvCurrentGrowth.text = "成长值：${bean.growthValue}"
        binding.activeLayoutHeader.activeHeaderProcessBarGrowth.max = growthVoMax(bean.growthValue)
        binding.activeLayoutHeader.activeHeaderProcessBarGrowth.progress = bean.growthValue
        ImageLoader.load(requireActivity(), bean.growthIcon, binding.activeLayoutHeader.activeHeaderIvCurrentLv)
        ImageLoader.load(requireActivity(), bean.nextGrowthIcon, binding.activeLayoutHeader.activeHeaderIvNextLv)
    }

    private fun handleSignInButton(enable: Boolean) {
        if (enable) {
            binding.activeLayoutSign.activeSignBtnSignIn.text = "立即领取"
            binding.activeLayoutSign.activeSignBtnSignIn.setBackgroundResource(R.drawable.comm_btn_red)
            binding.activeLayoutSign.activeSignBtnSignIn.isEnabled = true
        } else {
            binding.activeLayoutSign.activeSignBtnSignIn.text = "明天再来"
            binding.activeLayoutSign.activeSignBtnSignIn.setBackgroundResource(R.drawable.comm_btn_gray)
            binding.activeLayoutSign.activeSignBtnSignIn.isEnabled = false
        }
    }

    private fun handleSignInFlower(day: Int) {
        if (day > 0) {
            binding.activeLayoutSign.activeSignTvTitle.text = "已经连续签到${day}天"
        } else {
            binding.activeLayoutSign.activeSignTvTitle.text = "天天签到领小红花"
        }
        when (day) {
            1 -> binding.activeLayoutSign.activeSignIvDay1.setImageResource(R.drawable.img_tools_flower_sign)
            2 -> {
                binding.activeLayoutSign.activeSignIvDay1.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay2.setImageResource(R.drawable.img_tools_flower_sign)
            }
            3 -> {
                binding.activeLayoutSign.activeSignIvDay1.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay2.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay3.setImageResource(R.drawable.img_tools_flower_sign)
            }
            4 -> {
                binding.activeLayoutSign.activeSignIvDay1.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay2.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay3.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay4.setImageResource(R.drawable.img_tools_flower_sign)
            }
            5 -> {
                binding.activeLayoutSign.activeSignIvDay1.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay2.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay3.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay4.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay5.setImageResource(R.drawable.img_tools_flower_sign)
            }
            6 -> {
                binding.activeLayoutSign.activeSignIvDay1.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay2.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay3.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay4.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay5.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay6.setImageResource(R.drawable.img_tools_flower_sign)

            }
            7 -> {
                binding.activeLayoutSign.activeSignIvDay1.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay2.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay3.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay4.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay5.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay6.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay7.setImageResource(R.drawable.img_tools_flower_sign)
            }
            else -> {
                binding.activeLayoutSign.activeSignIvDay1.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay2.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay3.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay4.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay5.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay6.setImageResource(R.drawable.img_tools_flower_sign)
                binding.activeLayoutSign.activeSignIvDay7.setImageResource(R.drawable.img_tools_flower_sign)
            }
        }
    }

    private fun updatePagerHeightForChild(view: View, pager: ViewPager2) {
        view.post {
            val wMeasureSpec = View.MeasureSpec.makeMeasureSpec(view.width, View.MeasureSpec.EXACTLY)
            val hMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            view.measure(wMeasureSpec, hMeasureSpec)
            if (pager.layoutParams.height != view.measuredHeight) {
                pager.layoutParams = (pager.layoutParams).also { lp ->
                    lp.height = view.measuredHeight
                }
            }
        }
    }
}